<template>
    <div class="aite" :style="{ bottom: `${sendIptHeight + 90}px` }" @click="scrollToTarget" v-if="showScrollButton">
        <i class="EachApp EachApp_xiangshangshuangjiantou"></i>有人@我
    </div>
</template>
<script lang="ts" setup>
import type { chatListEntity } from '@/entity/im/ImEntity';
const props = defineProps<{
    chatList: chatListEntity[];
    chatRef: HTMLDivElement | null;
    itemRefs: Record<string, HTMLElement>;
    positionId: number;
    sendIptHeight: number;
}>()
const emit = defineEmits(['handleAite']);
const showScrollButton = ref(false);
const targetId = ref(null);

// 修复1：使用更精确的可见性检查
const checkVisibility = async (id: any) => {
    await nextTick();
    const element = props.itemRefs[id];
    if (!element) return false;
    const container = props.chatRef;
    if (!(container instanceof HTMLElement)) return false;
    const containerRect = container.getBoundingClientRect();
    const elementRect = element.getBoundingClientRect();
    return (
        elementRect.top >= containerRect.top && elementRect.bottom <= containerRect.bottom
    )
}

const handleNewData = async (newId: any) => {
    if(newId){
        targetId.value = newId;
        const isVisible = await checkVisibility(newId);
        showScrollButton.value = !isVisible;
    }
}

const scrollToTarget = () => {
    // 先判断@我的消息是否在当前以获取的数据中, 不在则请求接口去获取位置的上下位，如果在则直接滚动到该位置
    const isHave = props.chatList.some(item => item.id === props.positionId);
    return emit('handleAite', isHave);
}

// 修复3：改进的滚动到底部方法
const scrollToBottom = async () => {
    await nextTick()
    if (props.chatRef) {
        props.chatRef.scrollTo({
            top: props.chatRef.scrollHeight,
            behavior: 'auto'
        })
    }
}

// 修复4：挂载时确保完全滚动到底部
onMounted(async () => {
    await scrollToBottom();
    // 修复5：强制重新检查可见性
    await nextTick();
    await handleNewData(props.positionId);
})

defineExpose({
    handleNewData,
    scrollToTarget
})
</script>
<style lang="scss" scoped>
.aite{
    position: fixed;
    right: -120px;
    z-index: 999;
    background: white;
    bottom: 280px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 20px;
    border: 1px solid #ddd;
    color: var(--blue);
    font-weight: bold;
    padding: 9px 22px;
    cursor: pointer;
    animation: moveLeft 0.3s ease-in-out forwards;
    i{
        margin-right: 3px;
    }
}
/* 定义动画 */
@keyframes moveLeft {
    from {
        transform: translateX(0);
    }
    to {
        transform: translateX(-150px);
    }
}
</style>
